package com.taomus.mytools.helper.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cn.mytools.test.entity.Configure;
import com.cn.mytools.test.entity.Plugins;
import com.taomus.mytools.helper.ObjectHelper;
import com.taomus.mytools.helper.StringHelper;
import com.taomus.mytools.helper.stream.StreamHelper;
import com.taomus.mytools.helper.xml.annotations.Element;

public class XMLHelper{
	final static Logger LOG = LoggerFactory.getLogger(XMLHelper.class);

	public String toXML(Object src) throws Exception {
		return new ToXmlMapping().mapping(src);
	}

	public <T> T fromXML(String src, Class<T> dest)
			throws DocumentException, InstantiationException, IllegalAccessException {
		Document doc = null;
		doc = DocumentHelper.parseText(src);
		Object obj = dest.newInstance();
		Element elm = dest.getAnnotation(Element.class);
		String root = "/";
		if(ObjectHelper.isNotNull(elm)){
			root += StringHelper.defaultIfEmpty(elm.value(), dest.getSimpleName().toLowerCase());
		}
		new FromXmlMapping().mapping(doc, obj, dest.getDeclaredFields(), root);
		return (T) obj;
	}
	
	public static void main(String[] args) throws Exception{
		String path = System.getProperty("user.dir");
		System.out.println(path);
		File file = new File(path+"/bin/test.xml");
		String content = StreamHelper.getContent(new FileInputStream(file));
		System.out.println(content);
		XMLHelper xmlHelper = new XMLHelper();
		Plugins ps = xmlHelper.fromXML(content,Plugins.class);
		ps.getPlugin().forEach(a->System.out.println(a.toString()));
		
		System.out.println("------");
		
		String c = xmlHelper.toXML(ps);
		System.out.println(c);
		
	}
}